/**
 * Created by no1 on 2015/7/24.
 */
'use strict';
var DD = require('./daoLoader');
let F = require('../function')
let Base = require('./Base');
let util = require("util");
let VendorMongoDao = new DD.mongoDB.VendorDao();
let mysqlUsetDao = new DD.mysqlDB.UserDao()

let arr = ['name', 'address', 'settled'];
let arrOnfo = ['images', 'officerName', 'officerTel', 'officerEmail'
  , 'financeName', 'financeTel', 'serviceName', 'serviceTel', 'licenseType', 'licenseNo', 'licenseName', 'licenseExpired', 'licenseImage'
  , 'licenseIDImgFront', 'licenseIDImgBack', 'bankName', 'bankAddress', 'bankBranchName', 'cardName', 'cardNo'];
let getList = function* (parameters, opt, pageInfo, isSort, isPaging) {
  let retData = {}
    , ret
    , retCount
  //查询商家列表
  ret = yield VendorMongoDao.getByQueryPor(parameters, opt, pageInfo, isSort);
  if (ret.error == 1) return F.returnData(1, ret.msg);
  retData.retDataList = ret.data;

  if (isPaging == 1) {
    //查询商家列表的总条数
    retCount = yield VendorMongoDao.getCountByQuery(parameters);
    if (retCount.error == 1) return F.returnData(1, retCount.msg);
    retData.count = retCount.data;
  }
  return F.returnData(0, ret.msg, retData)
}


function VendorDispatcher(data) {
  data = data || {};
  data.dao = data.dao || VendorMongoDao;
  data.esDao = data.esDao || {};
  data.redisDao = data.redisDao || {};
  data.modelName = data.modelName || 'vendor';
  data.modelType = data.modelType || 'mongo';
  this.data = data;
  Base.call(this, this.data);
};
util.inherits(VendorDispatcher, Base);

/**
 * @todo 添加
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
VendorDispatcher.prototype.add = function*(fields) {

  let parameters = {};
  for (let one of arr) parameters[one] = fields[one];
  if (!parameters.name) return F.returnData(1, '请添加名字', 3);
  parameters.status = 1;
  parameters.type = 2;
  parameters.settled || (parameters.settled = 0);
  if (parameters.settled == 1) for (let one of arrOnfo) parameters[one] = fields[one];

  //根据code查询并拼接地理位置
  if (!!fields.disCodes) {
    let retdis = yield F.getDataFromDispatcher('districtDispatcher', 'findByDis', {code: {$in: fields.disCodes}});
    if (retdis.error == 1) return F.returnData(1, '地区编码有误')
    parameters.district = retdis.data;
  }
  let ret = yield this.dao.findAndSave({name: parameters.name}, parameters);
  if (ret.error == 1) return F.returnData(1, ret.msg, ret.data);
  return F.returnData(0, ret.msg, ret.data);
};
/**
 *@todo 修改
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
VendorDispatcher.prototype.update = function*(fields) {
  if (!fields.id) return F.returnData(1, '必须有商家id');
  let parameters = {};
  let arrAll = arr.concat(arrOnfo);
  for (let one of arrAll) if (!!fields[one] || fields[one] != null) parameters[one] = fields[one];
  if (fields.status != null) parameters.status = fields.status;
  if (fields.hasBoundUser != null) parameters.hasBoundUser = fields.hasBoundUser;

  //根据code查询并拼接categories
  if (!!fields.disCodes) {
    let retdis = yield F.getDataFromDispatcher('districtDispatcher', 'findByDis', {code: {$in: fields.disCodes}});
    if (retdis.error == 1) return F.returnData(1, '地区编码有误');
    parameters.district = retdis.data;
  }
  //更新数据
  let ret = yield this.dao.findAndUpdate({id: fields.id}, parameters, false);
  if (ret.error == 1) return F.returnData(1, ret.msg);

  let json = JSON.parse(JSON.stringify({data: ret.data}));
  let retData = F.dataFilter(json, ['_id', 'createdAt', 'updateAt', '__v', '__t']);
  return F.returnData(0, ret.msg, retData.data);

};

/**
 * @todo 获取列表
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
VendorDispatcher.prototype.list = function*(fields) {
  let parameters = {}
    , ret
    , retDataList
    , count
    , opt = {}
    , retData = {}
    , isPaging = fields.isPaging || 0
    , page = fields.page || 1
    , pageSize = fields.pageSize || 50
    , arr = ['id', 'name', 'type', 'status', 'settled', 'district', 'officerTel', 'hasBoundUser']

  for (let one of arr) opt[one] = 1;
  //拼接查询条件
  if (!!fields.type) parameters.type = fields.type;
  if (fields.settled != null) parameters.settled = fields.settled;
  if (fields.status != null) parameters.status = fields.status;
  if (!!fields.district) parameters['district.code'] = fields.district;
  if (!!fields.query) {
    let str = fields.query.replace(/[\+]*[\*]*[\?]*[\$]*[\^]*[\\]*/g, '');
    str = str.split('').join('+[\\s\\S]*');
    let re = new RegExp(str, 'i');
    parameters.name = {$regex: re};
  }
  //默认查询商家列表
  if (fields.act == 1) {
    ret = yield getList(parameters, opt, {page: page, pageSize: pageSize}, {id: -1}, isPaging);
    if (ret.error == 1) return F.returnData(1, ret.msg);
    retDataList = ret.data.retDataList;
    if (!!ret.data.count) count = ret.data.count;
  }
  //后台更多数据,主要是多了门店的数量
  else if (fields.act == 2) {
    let vids = [], vidSeted = [], countList = [], tmp = []
    parameters.type = 2;
    //查询商家列表
    ret = yield getList(parameters, opt, {page: page, pageSize: pageSize}, {id: -1}, isPaging);
    if (ret.error == 1) return F.returnData(1, ret.msg);
    retDataList = ret.data.retDataList;
    if (!!ret.data.count) count = ret.data.count;

    for (let one of retDataList) {
      vids.push(one.id);
      if (one.hasBoundUser == 1) vidSeted.push(one.id);
    }
    //查询sellUser获取uid
    let retSetedSelluser = yield F.getDataFromDispatcher('sellUserDispatcher', 'findByDis', {
      vid: {$in: vidSeted},
      primary: 1,
      status:1
    });
    if (retSetedSelluser.error == 1) return F.returnData(1, retSetedSelluser.msg);
    for (let one of vids) {
      //查询shop获取
      let retShopCount = yield F.getDataFromDispatcher('shopDispatcher', 'findCountByDis', {vendorid: one});
      if (retShopCount.error == 1) return F.returnData(1, retShopCount.msg);
      let tmp = {id: one, count: retShopCount.data || 0};
      countList.push(tmp);
    }

    for (let one of retDataList) {
      for (let user of retSetedSelluser.data) {
        if (one.id == user.vid) {
          one.mobile = user.mobile || "";
          one.sellUserid = user.id || 0;
          break;
        }
        else {
          one.mobile = "";
          one.sellUserid = 0;
        }
      }
      for (let count of countList) if (one.id == count.id) one.shopCount = count.count || 0;
      tmp.push(one);
    }
    retDataList = tmp;
  }
  //过滤数据
  let json = JSON.parse(JSON.stringify({data: retDataList}));
  retDataList = F.dataFilter(json, ['_id']);
  retDataList = retDataList.data;

  //拼接返回数据结构
  if (isPaging == 1) {
    retData.list = retDataList;
    retData.count = count;
  }
  else retData = retDataList;
  return F.returnData(0, ret.msg, retData);
};

/**
 * @todo 获取详情
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
VendorDispatcher.prototype.detail = function*(fields) {
  let arrDel = ['_id', 'createdAt', 'updateAt', 'categories', '__v', '__t']
    , opt = {};
  for (let one of arrDel) opt[one] = 0;
  let ret = yield  this.dao.getOneByQuery({id: fields.id}, opt);
  if (ret.error == 1) return F.returnData(1, ret.msg, ret.data);
  return F.returnData(0, ret.msg, ret.data);
};

/**
 * 内部调用
 * @param Qut
 * @returns {{error, msg, data}|{error, msg}}
 */
VendorDispatcher.prototype.findByDis = function*(Que) {
  let arr = ['id', 'name', 'type', 'status', 'settled']
    , opt = {};
  for (let one of arr) opt[one] = 1;
  let ret = yield  this.dao.getByQuery(Que, opt);
  let json = JSON.parse(JSON.stringify({data: ret.data}));
  let retData = F.dataFilter(json, ['_id']);
  if (ret.error == 1) return F.returnData(1, ret.msg, retData.data);
  return F.returnData(0, ret.msg, retData.data);
}

module.exports = VendorDispatcher;